<template>
  <div class="departments" v-loading="isLoading" element-loading-spinner="el-icon-loading">
    <el-card class="box-card">
      <!-- 第一行 -->
      <tree-tool
        :treeNode="company"
        :isRoot="true"
        @addDept="doAdd"
      ></tree-tool>
      <el-divider></el-divider>
      <el-tree
        :data="data"
        :props="defaultProps"
        node-key="id"
        default-expand-all
        :expand-on-click-node="false"
      >
        <!-- 把data传递给这个组件里的treeNode -->
        <tree-tool
          slot-scope="{ data }"
          :treeNode="data"
          @delDept="getDepList"
          @addDept="doAdd"
          @editDept="doEdit"
        />
      </el-tree>
      <addDepts
        ref="addDepts"
        :pid="currentId"
        :showDialog.sync="showDialog"
        @addDept="getDepList"
      />
    </el-card>
  </div>
</template>

<script>
// 导入封装的树状结构组件
import treeTool from './components/tree-tool'
// 导入封装好的编辑框的组件
import addDepts from './components/add-depts.vue'
// 导入发送请求的函数
import { getDepartments } from '@/api/departments'
// 导入封装的树状函数
import { transToTreeData } from '@/utils'
export default {
  name: 'depts',
  components: {
    treeTool,
    addDepts
  },

  data () {
    return {
      // 加载动画
      isLoading:true,
      // 用来控制新增窗口的显示和隐藏
      showDialog: false,
      // 用来记录当前被点的id
      currentId: '',
      company: {
        name: '江苏传智播客科技股份有限公司',
        manager: '负责人'
        // id:''
      },
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      data: [
        {
          id: 1,
          name: '总裁办',
          manager: '孙权',
          children: [
            {
              id: 11,
              name: '教学办',
              manager: '星爷'
            }
          ]
        },
        {
          id: 2,
          name: '行政部',
          manager: '张国荣'
        },
        {
          id: 3,
          name: '人事部',
          manager: '刘亚飞'
        }
      ]
    }
  },
  created () {
    this.getDepList()
  },
  methods: {
    async getDepList () {
      this.isLoading=true
      let res = await getDepartments()
      // console.log(res)
      //  修改公司名
      this.company.name = res.data.companyName
      this.company.id = ''
      let list = res.data.depts
      // 调用树状函数的数组,赋值给data
      this.data = transToTreeData(list, '')
      this.isLoading=false
    },
    // 点击的新增子部门触发的
    doAdd (id) {
      this.currentId = id
      this.showDialog = true
    },
    async doEdit (id) {
      await this.$refs.addDepts.getDetail(id)
      this.showDialog = true
    }
  }
}
</script>

<style>
.box-card {
  margin: 20px;
  padding: 140px 120px;
}
</style>
